from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
import requests
from utils.utils import toMd5,saveFile
import os,stat
import time
import shutil
import zipfile
from pdf2docx import Converter
from django.http import StreamingHttpResponse
from django.http import FileResponse
from django.utils.encoding import escape_uri_path
from django.core.signals import request_finished
from apps.translate.signal import deleteSrcData
from apps.translate.config import pdftoword_base_path

class PdfToWordAPIView(APIView):
    def post(self, request):
        data = saveFile(self, request, savepath=pdftoword_base_path)
        try:
            for i in data:
                position = os.path.join(pdftoword_base_path, i+'.pdf')
                docx_file = pdftoword_base_path+'%s.%s' % (i, 'docx')
                cv = Converter(position)
                cv.convert(docx_file, start=0, end=None)
            cv.close()
        except Exception as e:
            return Response({'code': 4000, 'msg': '转换失败'})   
        return Response({'code': 2000, 'msg': '转换完成', 'data': data})
        


class GetPdfToWordAPIView(APIView):
    def post(self, request):
        print(request.data)
        # 移动转行后的文件夹,如果是多个文件，则返回zip，一个的话直接返回xx.pdf
        if len(request.data)>1:
            secret_dir = toMd5(str(time.time()))
            path = pdftoword_base_path+"%s"%secret_dir
            os.makedirs(path)
            try:
                for i in request.data:
                     shutil.move(pdftoword_base_path+str(i)+'%s'%'.docx', path)
                     shutil.move(pdftoword_base_path+str(i)+'%s'%'.pdf', path)
                file_news = secret_dir +'.zip'
                z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
                for dirpath, dirnames, filenames in os.walk(path):
                    fpath = path
                    fpath = fpath and fpath + os.sep or ''
                    for filename in filenames:
                        z.write(os.path.join(dirpath, filename), fpath + filename)
                z.close()
                # shutil.move(secret_dir+'.zip', path)
                response = FileResponse(open(path+'/%s' %file_news, 'rb'))         
                response['Content-Type'] = "application/zip"       
                response['Content-Disposition'] = 'attachment;filename="%s"' % file_news 
                request_finished.send(sender='pdftowords',md5Items=[secret_dir])   
                return response
            except Exception as e:
                return Response({'code': 4001, 'msg': e.args})
        else:
            file_news = request.data[0]
            file_name = file_news+'.docx'
            response = FileResponse(open(pdftoword_base_path+'%s'%file_name, "rb"))
            response["Content-Type"] = "application/octet-stream"
            response["Content-Disposition"] = "attachment; filename*={}".format(escape_uri_path(file_name))
            request_finished.send(sender='pdftoword',md5Items=[file_news])   
            return response
 